<template>
  <div>
    <div class="node" v-has="{action: 'order:wx:list', effect: 'move'}">
      <!-- 搜索 -->
      <div :class="[$style.search_box ,$style.radus, $style.topSelect]">
        <SearchInput
          placeholder="订单编号"
          label="订单编号"
          style="margin-right:20px"
          :value="searchs.oid"
          :onChange="(val) => changeSearch('oid',val)"
          :onBlur="getRate"
        />
        <SearchInput
          placeholder="请输入"
          label="支付编号"
          style="margin-right:20px"
          :value="searchs.wxSn"
          :onChange="(val) => changeSearch('wxSn',val)"
          :onBlur="getRate"
        />
        <SearchInput
          placeholder="请输入"
          label="车牌号"
          style="margin-right:20px"
          :value="searchs.plate"
          :onChange="(val) => changeSearch('plate',val)"
          :onBlur="getRate"
        />
        <SearchInput
          placeholder="请输入"
          label="手机号"
          style="margin-right:20px"
          :value="searchs.phone"
          :onChange="(val) => changeSearch('phone',val)"
          :onBlur="getRate"
        />
      
        <div :class="$style.selectBox">
          <label>订单状态：</label>
          <el-select
            style="width:160px"
            v-model="searchs.state"
            clearable
            @change="getRate"
            placeholder="请选择状态"
          >
            <el-option label="等待处理中" :value="1"></el-option>
            <el-option label="充电中" :value="2"></el-option>
            <el-option label="充电取消" :value="3"></el-option>
            <el-option label="充电完成" :value="4"></el-option>
            <el-option label="充电异常" :value="5"></el-option>
            <el-option label="充电失败" :value="6"></el-option>
          </el-select>
        </div>
        <div :class="$style.selectBox">
          <label>结算状态：</label>
          <el-select
            style="width:160px"
            v-model="searchs.settlement"
            clearable
            @change="getRate"
            placeholder="请选择状态"
          >
          <el-option label="已结算" :value="1"></el-option>
          <el-option label="未结算" :value="0"></el-option>
            
          </el-select>
        </div>
        <div :class="$style.selectBox" style="margin-right:20px;display: flex;align-items: center;">
          <label>创建时间：</label>
          <el-date-picker
            v-model="searchs.appointmentTime"
            type="datetimerange"
            @change="timeChange('appointmentTime')"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          
            value-format="timestamp"
            :picker-options="pickerOptions"
            style="height:40px"
          ></el-date-picker>
        </div>
        <div :class="$style.selectBox" style="margin-right:20px;display: flex;align-items: center;">
          <label>订单结算时间：</label>
          <el-date-picker
            v-model="searchs.appointmentTimeEnd"
            type="datetimerange"
            @change="getRate"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            :picker-options="pickerOptions"
            style="height:40px"
          ></el-date-picker>
        </div>
        <div :class="$style.selectBox">
              <label>请选择：</label>
              <el-select clearable v-model="searchs.siteId" @change="changeSite('siteId')" placeholder="站点">
                <el-option
                  v-for="item in siteList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-select clearable v-model="searchs.pileId" @change="changePile('pileId')" placeholder="选择桩">
                <el-option
                  v-for="item in pileList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <el-select clearable v-model="searchs.gunId" @change="changeGun('gunId')" placeholder="选择枪">
                <el-option
                  v-for="item in gunList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
        </div>
        
      </div>
      <div :class="$style.exportbox">
        <button v-has="{action: 'export:wx:order', effect: 'move'}" type="button" @click="exportData" :class="$style.export">导出数据</button>
      </div>
      <!-- 统计 -->
      <div :class="[$style.amountbox]">
        <div :class="[$style.titlebox]">数据总览</div>
        <div :class="[$style.total,$style.radus]">
          <div :class="[$style.linedo]"></div>
          <div :class="[$style.totalNum]">
            <div>{{count.total}}</div>
            <div>订单金额</div>
          </div>
          <div :class="[$style.totalleft]">
            <div >
            <div>电费</div>
            <div>{{count.powerPrice}}</div>
          </div>
          <div >
            <div>服务费</div>
            <div>{{count.servicePrice}}</div>
          </div>
          </div>
        </div>

        <div :class="[$style.mingxi]">
          <div :class="[$style.items,$style.radus]"> 
            <div :class="[$style.linedo]"></div>
            <div :class="[$style.totalNum]">
              <div>{{count.electricity}}</div>
              <div>电量(度)</div>
            </div>
          </div>
          <div :class="[$style.items,$style.radus]">
            <div :class="[$style.linedo]"></div>
            <div :class="[$style.totalNum]">
              <div>{{count.chargeNum}}</div>
              <div>单数(笔)</div>
            </div>
          </div>
          <div :class="[$style.items,$style.radus]">
            <div :class="[$style.linedo]"></div>
            <div :class="[$style.totalNum]">
              <div>{{count.shi}}小时{{count.fen}}分</div>
              <div>时长</div>
            </div>
          </div>
        </div>
      </div>
      <Panel title="小程序订单">
        <!-- <div slot='ext' :class="$style.examine">
          <div class="adopt" @click="()=>editStore()">新增</div>
      </div> -->
      <TableEncapsulation
        slot="body"
        :tableConfig="tableConfig"
        :tableData="tableData"
      >
      <template slot="operation" slot-scope="operation">
            <el-button
              v-has="{action: 'order:wx:info', effect: 'move'}"
              type="text"
              @click="()=>commentDetail(operation.row.oid)"
            >查看</el-button>
            <el-button
              v-has="{action: 'order:control:stop', effect: 'move'}"
              v-if="operation.row.state==2"
              type="text"
              @click="()=>remove(operation.row.oid)"
            >停止充电</el-button>
          </template>
          <TablePager
            slot="pager"
            v-if="pager.use"
            :size="pager.size"
            :pageChange="pageChange"
            :show-total="pager.showTotal"
            :total="pager.total"
            :current="pager.current"
          >
            <span class="demonstration">GO></span>
          </TablePager>
      </TableEncapsulation>
      </Panel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'order:wx:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import { dateFormat } from "@/tools/time";
import requestService from "@/tools/requestExport";
import qs from 'qs';
export default {
  name: "orderWx",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput
  },
  data() {
    return {
      action:this.$baseUrl+'/export/wx/order?token='+localStorage.getItem('token'),
      searchs:{
        component: 'wxmini',
        gunId:'',
        siteId:"",
        pileId :"",
        groups:['api'],
        page: 1,
        oid:'',
        state:'',
        phone: '',
        plate: '',
        wxSn: '',
        settlement: '',
        appointmentTime:[],
        appointmentTimeEnd:'',
      },
      siteList: [],
      pileList: [],
      gunList: [],
      tableData: [],
      operation: true,
      endTime:'',
      beginTime:'',
      settBeginTime:'',
      settEndTime:'',
      query: {
        page: 1
      },
      pager: {
        component: 'wxmini',
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      count:{},
     
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
    };
  },
  created() {
   
    let now = new Date().getTime() + 3600 * 1000 * 24
    let year = new Date(now).getFullYear()
    let month = new Date(now).getMonth() 
    let day = new Date(now).getDate()
    let last = new Date().getTime() - 3600 * 1000 * 24 * 6
    let lastYear =  new Date(last).getFullYear() 
    let LastMonth = new Date(last).getMonth() 
    let lastDay = new Date(last).getDate()
    this.searchs.appointmentTime = [ new Date(lastYear, LastMonth, lastDay, 0, 0,0), new Date(year, month, day, 0, 0,0)]
    this.endTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : ''
    this.beginTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : ''
    this.settBeginTime =  ''
    this.settEndTime =  ''
    this.searchsFnc()
    this.getRate();
    this.getAmount()
    this.iotSite()
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "订单号",
            type: "text",
            prop: "oid",
            align: "center"
          },
          {
            label: "用户",
            type: "text",
            prop: "nick",
            align: "center"
          },
          {
            label: "手机号",
            type: "text",
            prop: "phone",
            align: "center"
          },
          {
            label: "支付金额",
            type: "text",
            prop: "amount",
            align: "center"
          },
          {
            label: "充电量",
            type: "text",
            prop: "electricity",
            align: "center"
          },
          {
            label: "实收电费",
            type: "text",
            prop: "receivedPowerPrice",
            align: "center"
          },
          {
            label: "实收服务费",
            type: "text",
            prop: "receivedServicePrice",
            align: "center"
          },
          
          {
            label: "订单状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 0 ? "等待处理中" : val == 1 ? "充电处理中" : val == 2 ? "充电中" : val == 3 ? "充电取消" : val == 4 ? "充电完成": val == 5 ? "充电异常":"充电失败"
          },
          {
            label: "充电进度",
            type: "text",
            prop: "soc",
            align: "center",
            fnc: val => val  ? val+"%" : ''
          },
          {
            label: "更新时间",
            type: "text",
            prop: "createTime",
            align: "center"
          },
          {
            label: "错误信息",
            type: "text",
            prop: "errorMsg",
            align: "center"
          }, 
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    searchsFnc (){
      let searchs = this.$store.getters.searchs
      if(searchs &&searchs.component == 'wxmini'){
        this.searchs = searchs
      }
      let pager = this.$store.getters.pager
      if(pager &&pager.component == 'wxmini'){
        this.pager = pager
      }
    },
    async getRate() {
      let endTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : undefined
      let beginTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : undefined
      let settBeginTime = this.searchs.appointmentTimeEnd ? (dateFormat(this.searchs.appointmentTimeEnd[0],"yyyy-MM-dd HH:mm:ss")) : undefined
      let settEndTime = this.searchs.appointmentTimeEnd ? (dateFormat(this.searchs.appointmentTimeEnd[1],"yyyy-MM-dd HH:mm:ss")) : undefined
      let state =  this.searchs.state
      let oid = this.searchs.oid, wxSn = this.searchs.wxSn, plate = this.searchs.plate , phone = this.searchs.phone, settlement = this.searchs.settlement
      let page = this.pager.current
       let gunId = '', siteId = '', pileId = ''
      if(this.searchs.gunId){
        gunId = this.searchs.gunId
      }else{
        if(this.searchs.pileId){
          pileId = this.searchs.pileId
        }else {
          siteId = this.searchs.siteId
        }
      }
      let search = objectFilter({beginTime, endTime, state, oid, page, wxSn, plate, phone, gunId, siteId, pileId, settlement, settBeginTime, settEndTime })
      const res = await request({
        url: "/order/wx/list",
        method: "POST",
        data: search
      });
      this.tableData = res.page.list
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    async exportData(){
      let endTime = this.endTime
      let beginTime = this.beginTime
      let settBeginTime = this.settBeginTime
      let settEndTime = this.settEndTime
      let state =  this.searchs.state
      let settlement = this.searchs.settlement
       let gunId = '', siteId = '', pileId = ''
      if(this.searchs.gunId){
        gunId = this.searchs.gunId
      }else{
        if(this.searchs.pileId){
          pileId = this.searchs.pileId
        }else {
          siteId = this.searchs.siteId
        }
      }
      let search = objectFilter({beginTime, endTime, state, gunId, siteId, pileId, settlement, settEndTime, settBeginTime })
      await requestService({
        url: "/export/wx/order",
        method: "POST",
        responseType: 'blob',
        data: qs.stringify(search)
      });
    },
    async changeSite(val){
      let url = '/iot/pile/select'
      let datas = {siteId:this.searchs.siteId}
      const res = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
      this.searchs.gunId = ''
      this.searchs.pileId = ''
      this.pager.current = 1;
      this.pileList = res.list
      this.getRate()
    },
    async changePile(){
      let url = '/iot/pile/gun/all'
      let datas = {pile:this.searchs.pileId}
      const res = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
      this.searchs.gunId = ''
      this.pager.current = 1;
      this.gunList = res.list
      this.getRate()
    },
        //站点
    async iotSite(){
      let { list } = await request({
      url: "/iot/site/select",
      method: "POST",
      data: {}
      });
       this.siteList = list
    },
    changeGun(){
      this.pager.current = 1;
      this.getRate()
    },
    timeChange(val){
      if(val == 'appointmentTime'){
        this.endTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : ''
        this.beginTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : ''
      }else{
        this.settBeginTime = this.searchs.appointmentTimeEnd ? (dateFormat(this.searchs.appointmentTimeEnd[0],"yyyy-MM-dd HH:mm:ss")) : ''
        this.settEndTime = this.searchs.appointmentTimeEnd ? (dateFormat(this.searchs.appointmentTimeEnd[1],"yyyy-MM-dd HH:mm:ss")) : ''
      }
      this.getRate()
      this.getAmount()
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    pageChange(val) {
      this.pager.current = val;
      this.getRate();
    },
    editStore(id){
      this.$router.push({ path: "/editStore",query:{id:id,} })
    },
    commentDetail(id){
      this.$store.commit('saveSearchs', this.searchs)
      this.$store.commit('savePager', this.pager)
      this.$router.push({ path: "/order/third/info",query:{id:id,type:'wx'} })
      // this.$router.push({ path: "/order/wx/info",query:{id:id} })
    },
    remove(id){
       this.$confirm('确认停充吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
       const del = await request({
                      url:'/order/control/stop/'+id,
                      method: "GET",
                    })
        if(del.code !==0) return
        this.$message.success('停充成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getRate()
      })
    },
    //总计
    async getAmount() {
      let endTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[1], "yyyy-MM-dd HH:mm:ss")) : undefined
      let beginTime = this.searchs.appointmentTime ? (dateFormat(this.searchs.appointmentTime[0],"yyyy-MM-dd HH:mm:ss")) : undefined
      let gunId = this.searchs.gunId
      let groups = this.searchs.groups
      let api = 0
      let search = objectFilter({beginTime, endTime, gunId, api })
      let { count } = await request({
        url: "/order/count/statistics",
        method: "POST",
        data: search
      });
      count.total = (count.powerPrice + count.servicePrice).toFixed(2)
      let shi = count.chargeTime ? parseInt(count.chargeTime/3600) :0
        count.shi = shi >=10 ? shi : '0'+shi
      let fen  = count.chargeTime ? Math.ceil((count.chargeTime - (parseInt(count.chargeTime/3600))*3600)/60)  : 0
      count.fen = fen >=10 ? fen : '0'+fen
      this.count = count
    }
  }
}
</script>
<style lang='scss' module>
.export {
    color: #FFF;
    background-color: #F56C6C;
    border-color: #F56C6C;
    border: 1px solid #F56C6C;
    border-radius: 5px;
    padding: 10px;
}
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}
.exportbox {
    display: flex;
    justify-content: flex-end;
    background: #fff;
    padding-bottom: 5px;
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  // margin-bottom: 20px;
}
.amountbox {
  // height: 80px;
  padding-bottom: 10px;
  margin: 6px auto;
  background: #fff;
  .titlebox {
    padding: 10px 20px;
  }
  .total {
    display: flex;
    height: 65px;
    background: #f6f8f9;
    margin-left: 20px;
    padding: 10px 20px;
    align-items: center;


    .totalleft {
      font-size: 13px;
      color: gray;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    
  }
      .linedo {
      height: 70%;
      width: 4px;
      background: #d8831a;
      /* margin-left: 20px; */
      border-radius: 26px;
    }
.totalNum :nth-child(1){
      font-size: 30px;
      color: #4a4947;
      }
    .totalNum :nth-child(2){
      color: gray;
    font-size: 14px;
       }
}
    .totalNum {
      padding: 0 10px;
      
    }
.mingxi {
  display: flex;
  margin-left: 20px;
  margin-top: 10px;
  justify-content: space-between;
  .items {
    width: 28%;
    background: #f6f8f9;
    height: 66px;
    padding: 8px 20px;
    display: flex;
    align-items: center;
  }
}
.radus {
  border-radius: 5px;
}
</style>